import styles from './index.module.scss'
import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleDetail } from '@/store/action/article'
import { useParams } from 'react-router'
import { RootState } from '@/store'
import { sanitize } from 'dompurify'
import dayjs from 'dayjs'
import Skeleton from './components/Skeleton'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import ArticleFooter from './components/ArticleFooter'
import NoComment from './components/NoComment'
import CommentItem from './components/CommentItem'
import { getComments } from '@/store/action/comment'

export default function Article() {
  const dispatch = useDispatch()

  const params = useParams<{ id: string }>()

  const { detail } = useSelector((state: RootState) => state.article)
  const { comments } = useSelector((state: RootState) => state.comment)

  useEffect(() => {
    dispatch(getArticleDetail(params.id))
    dispatch(getComments({ source: params.id }))
  }, [dispatch, params.id])

  useEffect(() => {
    if (!detail.art_id) return

    hljs.configure({
      ignoreUnescapedHTML: true,
    })
    const code = document.querySelectorAll('.dg-html pre')
    if (code.length > 0) {
      return code.forEach((item: any) => hljs.highlightElement(item))
    }
  }, [detail.art_id])

  const authorRef = useRef<HTMLDivElement>(null)

  const wrapperRef = useRef<HTMLDivElement>(null)

  // useEffect(() => {
  //   if (!detail.art_id) return
  //   const scrollFn = () => {
  //     if ((authorRef.current as HTMLDivElement).getBoundingClientRect().y < 0) {
  //       console.log('滚动出去可视区外')
  //     }
  //   }
  //   wrapperRef.current?.addEventListener('scroll', scrollFn)
  // }, [detail.art_id])

  const [showAuthor, setShowAuthor] = useState(false)

  const commemtHeadRef = useRef<HTMLDivElement>(null)

  const onShowComment = () => {
    // console.log('滚到评论去')
    wrapperRef.current?.scroll({
      top:
        commemtHeadRef.current!.offsetTop -
        commemtHeadRef.current!.offsetHeight,
    })
  }

  const handleScroll = () => {
    if ((authorRef.current as HTMLDivElement).getBoundingClientRect().y < 0) {
      console.log('滚动出去可视区外')
      setShowAuthor(true)
    } else {
      setShowAuthor(false)
    }
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {showAuthor ? (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span className="follow">关注</span>
            </div>
          ) : (
            ''
          )}
        </NavBar>

        <div className="wrapper" ref={wrapperRef} onScroll={handleScroll}>
          <div className="article-wrapper" hidden={!!detail.art_id}>
            {/* 骨架屏占位效果 */}
            <Skeleton />
          </div>
          <div className="article-wrapper" hidden={!detail.art_id}>
            {/* 文章描述信息栏 */}
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>
                  {dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
                </span>
                <span>{10} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
                <img src={detail.aut_photo} alt="" />
                <span className="name">{detail.aut_name}</span>
                <span className="follow">关注</span>
              </div>
            </div>

            {/* 文章正文内容区域 */}
            <div className="content">
              <div
                className="content-html dg-html"
                dangerouslySetInnerHTML={{ __html: sanitize(detail.content) }}
              ></div>
              <div className="date">
                发布文章时间：
                {dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
              </div>
            </div>
            <div className="divider"></div>
            <div className="comment">
              {/* 评论总览信息 */}
              <div className="comment-header" ref={commemtHeadRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>
              {/* 评论列表 */}
              {detail.comm_count === 0 ? (
                <NoComment />
              ) : (
                comments.results?.map((item) => (
                  <CommentItem key={item.com_id} comment={item} />
                ))
              )}
            </div>
          </div>
        </div>
        <ArticleFooter onShowComment={onShowComment} />
      </div>
    </div>
  )
}
